from django.contrib.auth.backends import ModelBackend
from user.models import UserModel
from django.db.models import Q

# 辅助函数，根据账号（用户名、手机号或邮箱）获取用户对象

def get_user_by_accout(accout):
    user = UserModel.objects.filter(Q(username=accout) | Q(phone=accout) | Q(email=accout)).first()
    return user

# 自定义的认证后端，继承自ModelBackend
class CoustomJwtModelBackends(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 如果没有提供用户名，尝试从kwargs中获取
        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)

        # 如果用户名或密码为空，则返回None
        if username is None or password is None:
            return None

        # 尝试获取用户对象
        user = get_user_by_accout(username)

        # 如果用户存在，并且密码正确，并且用户可以被认证，则返回用户对象
        if user and user.check_password(password) and self.user_can_authenticate(user):
            return user
